package monster.com.cvh.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.SkeletonScreen;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;
import monster.com.cvh.R;
import monster.com.cvh.activity.base.PermissionActivity;
import monster.com.cvh.adapter.NewsDetailAdapter;
import monster.com.cvh.bean.MessageEvent;
import monster.com.cvh.bean.NewsDetailBean;
import monster.com.cvh.bean.PostBean;
import monster.com.cvh.bean.PublishCommentBean;
import monster.com.cvh.listener.OnPublishListener;
import monster.com.cvh.manager.DialogManager;
import monster.com.cvh.util.EditTextDialog;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.SPUtils;
import monster.com.cvh.util.StatusBarUtil;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by ASUS on 2018/3/8.
 */

@SuppressLint("Registered")
public class NewsDetailsActivity extends PermissionActivity implements OnPublishListener {
    public Boolean isCollect = true;
    @BindView(R.id.iv_news_details_title_back)
    ImageView ivNewsDetailsTitleBack;
    @BindView(R.id.news_detail_recyclerview)
    RecyclerView newsDetailRecyclerview;
    @BindView(R.id.tv_comment)
    TextView tvComment;
    @BindView(R.id.iv_news_detail_comment)
    ImageView ivNewsDetailComment;
    @BindView(R.id.iv_news_detail_collection)
    ImageView mIvNewsDetailCollection;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rf_activity_news_details)
    SmartRefreshLayout rfActivityNewsDetails;
    @BindView(R.id.view_activity_news_loading)
    View mLoadingView;
    private List<NewsDetailBean.DataBean> mDatas = new ArrayList<>();
    private NewsDetailAdapter newsDetailAdapter;
    private LayoutInflater inflater;
    private Boolean showCommentIcon = true;
    private int mAId = 1;
    private int articleId;
    private int pageIndex = 0;
    private Gson gson;
    private Boolean sendCollect;
    private BaseBottomDialog mDialog;
    private List<NewsDetailBean.DataBean> data;
    private int replyNum;
    private String token = null;
    private String newsUrl;
    private TextView mTvReplyNum;
    private int postion;
    private int bannerPostion;
    private ProgressDialog mDialogLoging;
    private WebView webView;
    private  SkeletonScreen mSkeletonScreen;
    private Handler mHandler=new Handler();

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_news_details;
    }

    @Override
    protected void initEvent() {
    }

    /**
     * 删除评论
     */
    private void deleteComment() {
        newsDetailAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
                Log.i(" lixiaofei", "我是data的长度: " + mDatas.size());
                new AlertDialog.Builder(NewsDetailsActivity.this).setTitle("删除本条").setMessage("确认要删除本条数据吗？").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.i(" lixiaofei", "我是当前位置: " + position);
                        OkGo.<String>delete(MyConstant.DELETE_COMMENT).params("comment_id", mDatas.get(position).getId()).params("token", SPUtils.getString(NewsDetailsActivity.this, "token", ""))
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        Gson gson = new Gson();
                                        PostBean deleteBean = gson.fromJson(s, PostBean.class);
                                        switch (deleteBean.getCode()) {
                                            case 1:
                                                //删除成功
                                                showToastLong("删除成功");
                                                newsDetailAdapter.getData().remove(position);
                                                newsDetailAdapter.notifyDataSetChanged();
                                                EventBus.getDefault().post(new MessageEvent("adapter通知我更新ui了"));
                                                break;
                                        }
                                    }
                                });
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).show();


            }
        });
    }

    /**
     * 初始化foot
     */
    private void initFoot() {
        View footView = inflater.inflate(R.layout.item_news_foot, null, false);
        newsDetailAdapter.addFooterView(footView);
    }

    /**
     * 初始化头部
     */
    private void initHead() {
        inflater = LayoutInflater.from(this);
        View newWebView = inflater.inflate(R.layout.item_webview, null, false);
        newsDetailAdapter.addHeaderView(newWebView);
        webView = newWebView.findViewById(R.id.news_webview);
        final WebSettings webSettings = webView.getSettings();
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        rfActivityNewsDetails.setVisibility(View.VISIBLE);
                        mSkeletonScreen.hide();
                    }
                },1000);
            }
        });
        if (token == null || token.equals("")) {
            newsUrl = MyConstant.NEWSDETAIL + articleId;
        } else {
            newsUrl = MyConstant.NEWSDETAIL + articleId + "?token=" + SPUtils.getString(this, "token", "");
        }
        Log.i("lixiaofei", "initHead: " + newsUrl);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setUseWideViewPort(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.loadUrl(newsUrl);

        //添加评论个数
        View commentNum = inflater.inflate(R.layout.item_head_comment_num, null, false);
        mTvReplyNum = commentNum.findViewById(R.id.item_head_comment_num);
        mTvReplyNum.setText("全部评论" + "(" + replyNum + ")");
        newsDetailAdapter.addHeaderView(commentNum);
        mDialogLoging.dismiss();
    }

    /**
     * 监听Back键按下事件,方法2:
     * 注意:
     * 返回值表示:是否能完全处理该事件
     * 在此处返回false,所以会继续传播该事件.
     * 在具体项目中此处的返回值视情况而定.
     */
//    @Override
//    public boolean onKeyUp(int keyCode, KeyEvent event) {
//        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
//            Intent i = new Intent();
//            i.putExtra("article", sendCollect);
//            i.putExtra("postion",postion);
//            i.putExtra("bannerPostion",bannerPostion);
//            setResult(RESULT_OK, i);
////            EventBus.getDefault().post(new MessageEvent("adapter通知我更新ui了"));
//            finish();
//            return true;
//        }else {
//            return super.onKeyDown(keyCode, event);
//        }
//
//    }
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (webView != null) {
            if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
                webView.goBack();// 返回前一个页面
                return true;
            } else {
                Intent i = new Intent();
                i.putExtra("article", sendCollect);
                i.putExtra("postion", postion);
                i.putExtra("bannerPostion", bannerPostion);
                setResult(RESULT_OK, i);
//            EventBus.getDefault().post(new MessageEvent("adapter通知我更新ui了"));
                finish();

            }
        }
        return true;

    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {
        mDialogLoging = new ProgressDialog(this);
        mDialogLoging.setMessage(getResources().getString(R.string.wait));
        mDialogLoging.setOnKeyListener(new DialogInterface.OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                //回退键监听
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                }
                return false;
            }
        });
        mDialogLoging.setCanceledOnTouchOutside(false);
        //获取上个页面传来的位置
        postion = getIntent().getIntExtra("postion", 0);
        bannerPostion = getIntent().getIntExtra("bannerPostion", 0);
        //修改状态栏颜色
        StatusBarUtil.setStatusBarLightMode(NewsDetailsActivity.this, Color.WHITE);
        //获取token
        token = SPUtils.getString(NewsDetailsActivity.this, "token", "");
        postion = getIntent().getIntExtra("postion", -1);
        bannerPostion = getIntent().getIntExtra("bannerPostion", -1);
        //获取文章收藏状态
        boolean collect = getIntent().getBooleanExtra("isCollect", false);
        if (collect) {
            mIvNewsDetailCollection.setImageResource(R.mipmap.information_biglike_blue);
            isCollect = !isCollect;
        } else {
            mIvNewsDetailCollection.setImageResource(R.mipmap.information_biglike);
        }
        //初始化gson
        gson = new Gson();
        //获取上个页面的Url
        articleId = getIntent().getIntExtra("id", -1);
        Log.i("lixiaofei", "initData: " + articleId);
        replyNum = getIntent().getIntExtra("reply", -1);
        Log.i("lixiaofei", "initData: " + replyNum);
        Log.i("lixiaofei", "initData: " + MyConstant.GETCOMMENTS);
        getServiceComment();
        rfActivityNewsDetails.setEnableRefresh(false);
        /**
         * 上拉加载
         */
        rfActivityNewsDetails.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageIndex++;
//                newsDetailAdapter.removeAllHeaderView();
                getMoreComment();
                refreshlayout.finishLoadmore(500);
                if (data.size() < 20) {
                    showToastLong("没有更多评论");
                }
            }
        });

        mSkeletonScreen = Skeleton.bind(mLoadingView)
                .load(R.layout.webview_skeleton_layout)
                .duration(1000)
                .color(R.color.shimmer_color)
                .angle(0)
                .show();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        reSetComment();
    }

    private void getMoreComment() {
        /**
         * 获取更多文章评论
         */
        Log.i("lixiaofei", "getServiceComment: " + articleId);
        if (token.equals("") || token == null) {
            OkGo.<String>get(MyConstant.GETCOMMENTS).params("page_index", pageIndex).params("article_id", articleId).execute(new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    NewsDetailBean newsDetailBean = gson.fromJson(s, NewsDetailBean.class);
                    data = newsDetailBean.getData();
                    if (data != null) {
                        mDatas.addAll(data);
                    } else {
                        showToastLong("无更多数据");
                    }
                    newsDetailAdapter.notifyDataSetChanged();

                }
            });
        } else {
            OkGo.<String>get(MyConstant.GETCOMMENTS).params("page_index", pageIndex).params("article_id", articleId).params("token", SPUtils.getString(this, "token", ""))
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            NewsDetailBean newsDetailBean = gson.fromJson(s, NewsDetailBean.class);
                            data = newsDetailBean.getData();
                            if (data != null) {
                                mDatas.addAll(data);
                            }
                            newsDetailAdapter.notifyDataSetChanged();

                        }
                    });
        }

    }

    private void getServiceComment() {
        /**
         * 获取文章评论
         */
        Log.i("lixiaofei", "getServiceComment: " + articleId);
        if (token == null || token.equals("")) {
            mDialogLoging.show();
            OkGo.<String>get(MyConstant.GETCOMMENTS).params("page_index", pageIndex).params("article_id", articleId)
                    .execute(new StringCallback() {
                        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            NewsDetailBean newsDetailBean = gson.fromJson(s, NewsDetailBean.class);
                            data = newsDetailBean.getData();
                            if (data != null) {
                                mDatas.addAll(data);
                            }
                            newsDetailRecyclerview.setLayoutManager(new LinearLayoutManager(NewsDetailsActivity.this) {
                                @Override
                                public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                                    return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                            ViewGroup.LayoutParams.WRAP_CONTENT);
                                }
                            });

                            newsDetailAdapter = new NewsDetailAdapter(R.layout.item_news_detail, mDatas);
                            newsDetailRecyclerview.setAdapter(newsDetailAdapter);
                            newsDetailAdapter.notifyDataSetChanged();
                            /**
                             * 删除评论
                             */
                            deleteComment();
                            initHead();

                            initFoot();
                        }
                    });
        } else {
            mDialogLoging.show();
            OkGo.<String>get(MyConstant.GETCOMMENTS).params("page_index", pageIndex).params("article_id", articleId).params("token", SPUtils.getString(this, "token", ""))
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            NewsDetailBean newsDetailBean = gson.fromJson(s, NewsDetailBean.class);
                            data = newsDetailBean.getData();
                            if (data != null) {
                                mDatas.addAll(data);
                            }
                            newsDetailRecyclerview.setLayoutManager(new LinearLayoutManager(NewsDetailsActivity.this) {
                                @Override
                                public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                                    return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                            ViewGroup.LayoutParams.WRAP_CONTENT);
                                }
                            });

                            newsDetailAdapter = new NewsDetailAdapter(R.layout.item_news_detail, mDatas);
                            newsDetailRecyclerview.setAdapter(newsDetailAdapter);
                            newsDetailAdapter.notifyDataSetChanged();
                            /**
                             * 删除评论
                             */
                            deleteComment();
                            initHead();
                            initFoot();
                            mDialogLoging.dismiss();
                        }
                    });
        }


    }

    /**
     * 发表后重置
     */
    private void reSetComment() {
        /*
         * 获取文章评论
         */
        OkGo.<String>get(MyConstant.GETCOMMENTS).params("page_index", 0).params("article_id", articleId).params("token", SPUtils.getString(this, "token", ""))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        NewsDetailBean newsDetailBean = gson.fromJson(s, NewsDetailBean.class);
                        mDatas = newsDetailBean.getData();
                        newsDetailAdapter = new NewsDetailAdapter(R.layout.item_news_detail, mDatas);
                        initHead();
                        initFoot();
                        newsDetailRecyclerview.setLayoutManager(new LinearLayoutManager(NewsDetailsActivity.this, LinearLayoutManager.VERTICAL, false) {
                            @Override
                            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                                return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                        ViewGroup.LayoutParams.WRAP_CONTENT);
                            }
                        });
                        newsDetailRecyclerview.setAdapter(newsDetailAdapter);
                        newsDetailAdapter.notifyDataSetChanged();
                        deleteComment();
                        int newReply = replyNum + 1;
                        mTvReplyNum.setText("全部评论" + "(" + newReply + ")");

                    }
                });

    }

    /**
     * 后退按钮
     */
    @OnClick(R.id.iv_news_details_title_back)
    public void onIvNewsDetailsTitleBackClicked() {
        Intent i = new Intent();
        i.putExtra("article", sendCollect);
        i.putExtra("postion", postion);
        i.putExtra("bannerPostion", bannerPostion);
        setResult(RESULT_OK, i);
        finish();
    }


    /**
     * 评论框
     */
    @OnClick(R.id.tv_comment)
    public void onTvCommentClicked() {
        if (token.equals("") || token == null) {
            startActivity(new Intent(NewsDetailsActivity.this, LoginActivity.class));
        } else {
            EditTextDialog dialog = new EditTextDialog();
            int layoutRes = dialog.getLayoutRes();
            mDialog = BottomDialog.create(getSupportFragmentManager())
                    .setViewListener(new BottomDialog.ViewListener() {
                        @Override
                        public void bindView(View v) {
                            initView(v);
                        }
                    })
                    .setLayoutRes(layoutRes)
                    .setDimAmount(0.1f)            // Dialog window dim amount(can change window background color）, range：0 to 1，default is : 0.2f
                    .setTag("BottomDialog")     // setting the DialogFragment tag
                    .show();
        }
    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initView(View view) {
        final EditText commentContext = view.findViewById(R.id.edt_dialog_comment_context);
        //取消按钮
        view.findViewById(R.id.btn_dialog_comment_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
            }
        });
        /**
         * 确定按钮
         */
        view.findViewById(R.id.btn_dialog_comment_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (commentContext.getText().toString().trim().equals("")) {
                    showToastLong("请输入内容");
                } else {
                    OkGo.<String>post(MyConstant.CREATE_COMMENT).params("article_id", articleId).params("token", SPUtils.getString(NewsDetailsActivity.this, "token", ""))
                            .params("content", commentContext.getText().toString().trim()).execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            PublishCommentBean publishCommentBean = gson.fromJson(s, PublishCommentBean.class);
                            switch (publishCommentBean.getCode()) {
                                case 1:
                                    showToastLong("发布成功");
                                    reSetComment();
                                    mDialog.dismiss();
                                    break;
                            }
                        }
                    });
                }
            }
        });

    }

    /**
     * 评论按钮
     */
    @OnClick(R.id.iv_news_detail_comment)
    public void onIvNewsDetailCommentClicked() {
        if (showCommentIcon) {
            //跳到评论
            newsDetailRecyclerview.addOnScrollListener(new MyRecyclerViewScrollListener());
            newsDetailRecyclerview.scrollToPosition(1);
            ivNewsDetailComment.setImageResource(R.mipmap.information_repla_article);
            showCommentIcon = !showCommentIcon;
        } else {
            //跳到文章
            newsDetailRecyclerview.addOnScrollListener(new MyRecyclerViewScrollListener());
            newsDetailRecyclerview.scrollToPosition(0);
            ivNewsDetailComment.setImageResource(R.mipmap.information_repla_all);
            showCommentIcon = !showCommentIcon;

        }

    }

    @Override
    public void refreshData() {

    }


    /**
     * 收藏按钮
     */
    @OnClick(R.id.iv_news_detail_collection)
    public void onViewClicked() {
        if (token.equals("") || token == null) {
            startActivity(new Intent(NewsDetailsActivity.this, LoginActivity.class));
            finish();
        } else {
            if (isCollect) {
                //收藏
                OkGo.<String>post(MyConstant.COLLECTARTICLE).params("article_id", articleId).params("token", SPUtils.getString(this, "token", ""))
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                PostBean postBean = gson.fromJson(s, PostBean.class);
                                switch (postBean.getCode()) {
                                    case 1:
                                        //收藏成功
                                        showToastLong("收藏成功");
                                        mIvNewsDetailCollection.setImageResource(R.mipmap.information_biglike_blue);
                                        isCollect = !isCollect;
                                        sendCollect = true;
                                        EventBus.getDefault().post(new MessageEvent("adapter通知我更新ui了"));
                                        break;
                                    case -1006:
                                        mIvNewsDetailCollection.setImageResource(R.mipmap.information_biglike_blue);
                                        isCollect = !isCollect;
                                        sendCollect = true;
                                        break;
                                }
                            }
                        });
            } else {
                //取消收藏
                OkGo.<String>delete(MyConstant.CANCELCOLLECTARTICLE).params("article_id", articleId).params("token", SPUtils.getString(this, "token", ""))
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                PostBean bean = gson.fromJson(s, PostBean.class);
                                switch (bean.getCode()) {
                                    case 1:
                                        showToastLong("取消收藏成功");
                                        mIvNewsDetailCollection.setImageResource(R.mipmap.information_biglike);
                                        isCollect = !isCollect;
                                        sendCollect = false;
                                        EventBus.getDefault().post(new MessageEvent("adapter通知我更新ui了"));
                                        break;

                                }
                            }
                        });
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    //todo 空指针bug
    //滑动监听
    private class MyRecyclerViewScrollListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
            int firstVisibleItemPosition = manager.findFirstVisibleItemPosition();
            // 当不滚动时
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                // 判断是否滚动超过一屏
                if (firstVisibleItemPosition == 0) {
                    if (ivNewsDetailComment != null) {
                        ivNewsDetailComment.setImageResource(R.mipmap.information_repla_article);
                    }
                } else {
                    if (ivNewsDetailComment != null) {
                        ivNewsDetailComment.setImageResource(R.mipmap.information_repla_article);
                    }
                }

            }
        }
    }
}
